//
//  KLStatusPictureView.swift
//  BCWeiBo
//
//  Created by bcmac3 on 16/4/5.
//  Copyright © 2016年 KellenYangs. All rights reserved.
//

import UIKit
import SDWebImage

/// 选中照片通知
let KLStatusCellSelectPictureNotification = "KLStatusCellSelectPictureNotification"
/// URL 的 KEY
let KLStatusCellSelectPictureURLKey = "KLStatusCellSelectPictureURLKey"
/// IndexPath 的 KEY
let KLStatusCellSelectPictureIndexKey = "KLStatusCellSelectPictureIndexKey"

class KLStatusPictureView: UICollectionView {

    var status: KLStatus? {
        didSet {
            sizeToFit()
            
            // 刷新视图
            reloadData()
        }
    }
    
    override func sizeThatFits(size: CGSize) -> CGSize {
        return calculateImageSize()
    }
    /// 图片布局
    private let pictureLayout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        // 提示：调用父类的构造函数之前，必须给本类的属性初始化
        super.init(frame: frame, collectionViewLayout: pictureLayout)
        
        // 1.注册可重用cell
        registerClass(StatusPictureCell.self, forCellWithReuseIdentifier: KLPictureCellReuseIdentifier)
        
        // 2.设置数据源代理
        dataSource = self
        //        delegate = self
        
        // 3.设置其它属性
        backgroundColor = UIColor.lightGrayColor()
        
        // 4.设置间隙
        pictureLayout.minimumInteritemSpacing = 10
        pictureLayout.minimumLineSpacing = 10
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    /*
    0.没有图片, 返回zero
    1.单张图片, 返回图片实际大小
    2.多张图片, 图片大小固定
    2.1四张图片, 会按照田字格显示
    2.2其它多图, 按照九宫格显示
    */
    private func calculateImageSize() -> CGSize{
        
        
        // 0.获取图片的数量
        let count = status!.storedPictureURLs?.count
        let itemSize = CGSize(width: 90, height: 90)
        let margin:CGFloat = 10
        pictureLayout.itemSize = itemSize
        
        // 1.没有图片
        if count == 0 || count == nil
        {
            return CGSizeZero
        }
        // 2.单张图片
        if count == 1
        {
            // 2.1从缓存中拿到图片
            let key = status!.storedPictureURLs?.first?.absoluteString
            let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
            if image == nil
            {
                return CGSizeZero
            }
            pictureLayout.itemSize = image.size
            // 2.2返回大小
            return image.size
        }
        // 3.四张图片
        if count == 4
        {
            let width = itemSize.width * CGFloat(2) + margin
            return CGSize(width: width, height: width)
        }
        // 4.其它多图
        /*
        2,3 -> 1
        5,6 -> 2
        7,8,9 -> 3
        */
        let colCount = 3
        let rowCount = (count! - 1) / 3 + 1
        // 宽度 * 列数 + (列数 - 1) * 间隙
        let width = itemSize.width * CGFloat(colCount) + CGFloat(colCount - 1) * margin
        // 高度 * 行数 + (行数 - 1) * 间隙
        let height = itemSize.height * CGFloat(rowCount) + CGFloat(rowCount - 1) * margin
        return CGSize(width: width, height: height)
    }
    
}

let KLPictureCellReuseIdentifier = "KLPictureCellReuseIdentifier"

extension KLStatusPictureView: UICollectionViewDataSource
{
    // MARK: - UICollectionViewDataSource
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return status?.storedPictureURLs?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        // 1.取出cell
        let itemCell = collectionView.dequeueReusableCellWithReuseIdentifier(KLPictureCellReuseIdentifier, forIndexPath: indexPath) as! StatusPictureCell
        // 2.设置图片
        itemCell.imageURL = status?.storedPictureURLs![indexPath.item]
        // 3.返回cell
        return itemCell
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        // 拿到当前点击图片
        //        print(status?.pictureURLs![indexPath.item])
        //        print(status?.largePictureURLs![indexPath.item])
        
        // 发送通知, 通知控制器弹出图片浏览器
        NSNotificationCenter.defaultCenter().postNotificationName(KLStatusCellSelectPictureNotification,
            object: self,
            userInfo: [KLStatusCellSelectPictureURLKey: status!.largePictureURLs!,
                KLStatusCellSelectPictureIndexKey: indexPath])
    }
}

private class StatusPictureCell: UICollectionViewCell {
    var imageURL: NSURL?{
        didSet{
            iconView.sd_setImageWithURL(imageURL!)
            
            // 设置时候显示gif图片
            gifImageView.hidden =  ((imageURL!.absoluteString as NSString).pathExtension.lowercaseString != "gif")
        }
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        addSubview(iconView)
        iconView.addSubview(gifImageView)
        
        
        iconView.xmg_Fill(self)
        gifImageView.xmg_AlignInner(type: XMG_AlignType.BottomRight, referView: iconView, size: nil)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private lazy var iconView = UIImageView()
    private lazy var gifImageView:UIImageView = {
        let gifIv = UIImageView(image: UIImage(named: "timeline_image_gif"))
        gifIv.hidden = true
        return gifIv
    }()
}
